<template>
  <section>
    <el-popover v-if="waybillsTabel"
                ref="popover"
                placement="bottom-start"
                width="1200"
                trigger="click">
      <div class="titleSty">
        <span>合单子单 ></span>
      </div>
      <el-table :data="
          waybillsTabel.slice(
            (params.page - 1) * params.size,
            params.page * params.size
          )
        "
                style="width: 100%"
                max-height="300px"
                border>
        <template v-for="(item, index) in tableHeaderData">
          <el-table-column v-if="item.type === 'contractNo'"
                           :key="index"
                           :prop="item.type"
                           :label="item.label"
                           :width="`180px`">
            <template slot-scope="scope">
              <span>{{ scope.row.contractNo }}</span>
            </template>
          </el-table-column>
          <el-table-column v-else-if="item.type === 'fromInfo'"
                           :key="index"
                           :prop="item.type"
                           :label="item.label">
            <template slot-scope="scope">
              <span>{{ scope.row.customerName }}</span>
            </template>
          </el-table-column>
          <el-table-column v-else-if="item.type === 'toInfo'"
                           :key="index"
                           :prop="item.type"
                           :label="item.label">
            <template slot-scope="scope">
              <span>{{ scope.row.consigneeName }}</span>
            </template>
          </el-table-column>
          <el-table-column v-else-if="item.type === 'orderInfo'"
                           :key="index"
                           :prop="item.type"
                           :label="item.label">
            <template slot-scope="scope">
              <OrderInfo :row="scope.row" />
            </template>
          </el-table-column>
          <el-table-column v-else-if="item.type === 'car'"
                           :key="index"
                           :prop="item.type"
                           :label="item.label">
            <template slot-scope="scope">
              <CarInfo :row="scope.row" />
            </template>
          </el-table-column>
          <el-table-column v-else
                           :key="index"
                           :prop="item.type"
                           :label="item.label"
                           :width="`160px`">
            <template slot-scope="scope">
              {{scope.row[item.type] || '--' }}
            </template>
          </el-table-column>
        </template>
      </el-table>
      <div class="footerSty">
        <div>
          订单货物：总数量<span class="orange">{{ quantity }}</span>件，
          总重量<span class="orange">{{ calculateWeight.toFixed(2) || 0 }}</span>公斤，
          总体积<span class="orange">{{ calculateVolume.toFixed(2) || 0  }}</span>方，
          总运费<span class="orange">{{ totalFee || 0 }}</span>元
        </div>
        <el-pagination class="pagination"
                       :current-page="params.page"
                       :page-size="params.size"
                       :total="total"
                       :page-sizes="[5, 10, 15, 20]"
                       layout="total, sizes, prev, pager, next, jumper"
                       @size-change="handleSizeChange"
                       @current-change="handleCurrentChange">
        </el-pagination>
      </div>
      <div slot="reference"
           class="slot_sty">
        <i class="el-icon-caret-bottom icon_sty" />
        <div class="linkClass">
          <a href="javascript:void(0)"
             :title="contractNo"
             @click.stop="handleClick">{{ contractNo }}
          </a>
        </div>
        <span v-if="row.price && row.price.templateId"
              class="order-type"> 合约 </span>
        <i class="el-icon-copy-document icon_sty_1"
           @click.stop="copy(contractNo)" />
      </div>
    </el-popover>
  </section>
</template>

<script>
import OrderInfo from "@components/table/column/OrderInfo.vue"
import CarInfo from "@components/table/column/CarInfo.vue"
import { returnThousandDigit } from "@/libs/util.js";
import { quotation, transport } from "@/api/index";
export default {
  name: "ChildOrderInfo",
  inject: ['$table'],
  components: { OrderInfo, CarInfo },
  props: {
    contractNo: String,
    router: String,
    row: {
      type: Object,
      default: () => { }
    },
    isCombineQuoteFee: Number,
    target: String
  },
  data () {
    return {
      list: [],
      tableHeaderData: [
        { label: "合同编号", type: "contractNo" },
        { label: "发货方", type: "fromInfo" },
        { label: "收货方", type: "toInfo" },
        { label: "运输信息", type: "orderInfo" },
        { label: "车型信息", type: "car" },
        { label: "发货时间", type: "fromTime" },
        { label: "收货时间", type: "toTime" }
      ],
      params: {
        size: 5,
        page: 1
      },
      visible: false
    };
  },
  computed: {
    waybillsTabel () {
      return this.row.waybills;
    },
    calculateWeight () {
      return this.row.calculateWeight;
    },
    quantity () {
      return this.row.totalQuantity;
    },
    calculateVolume () {
      return this.row.calculateVolume;
    },
    totalFee () {
      if (this.row.totalFee || this.row?.price?.totalFee) {
        let fee = this.row.totalFee || this.row?.price?.totalFee;
        return returnThousandDigit(fee, 2)
      }
      return 0;
    },
    total () {
      let total = null
      if (this.row?.waybills?.length) {
        total = this.row?.waybills.length;
      }
      return total
    },
    tips () {
      return {
        4: "合单有关单待办需要处理，不能操作",
        5: "合单已对账，不能操作",
        6: "合单已结账，不能操作",
        7: "财务已将合单加入到对账单，不能操作，请联系财务处理"
      }
    },
    unValidStatus () {
      // 待审核、已关闭不用前置校验
      return [1, 32, 14];
    },
  },
  methods: {
    handleClick () {
      if (this.unValidStatus.includes(this.row.status) || this.isCombineQuoteFee) {
        this.goDetail(this.row.status);
      } else {
        this.quoteCheckValidate();
      }
    },
    //报价前置效验
    async quoteCheckValidate () {
      let response = await quotation.validateCheckQuotation(this.row.subjectId);
      if (response.code === 0) {
        if (response.data.validate) {
          // 待报价、草稿、被拒绝、补充报价需要调用validate接口再次校验
          if ([10, 0, 2, 3].includes(this.row.status)) {
            this.quoteValidate();
          } else {
            this.goDetail(this.row.status);
          }
        } else if ([4, 7].includes(response.data.flag)) {
          return this.$message({ type: 'warning', message: this.tips[response.data?.flag] })
        } else if ([5, 6].includes(response.data.flag)) {
          this.$confirm(
            this.tips[response.data?.flag],
            "提示",
            {
              confirmButtonText: "我知道了",
              type: "warning",
              showClose: false,
              showCancelButton: false,
              closeOnClickModal: false
            }
          ).then(() => {
            this.closeQuotaion(response.data.flag);
          });
        }
      } else {
        this.$message({ type: "error", message: response.message });
      }
    },
    async quoteValidate () {
      let { data } = await quotation.validateQuote(this.row.subjectId);
      // data.validate true: 对方没有报价 false：对方已报价
      if (data.validate) {
        // if (this.isMatch) {
        //   this.handleTableScheduler()
        // } else {
        this.goDetail(this.row.status);
        // }
      } else if (data.flag === 1) {
        this.$confirm("已向您发起了报价，是否去审核?", "提示", {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          // TODO: 跳转到审核页面
          this.goDetail("11", data.quotationId);
        });
      } else if (data.flag === 2) {
        this.$confirm("不能重复报价，请刷新页面?", "提示", {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          // 刷列表 
          this.$table.search();
        });
      }
    },
    // 关闭报价单
    async closeQuotaion (closeType) {
      await transport.closeCombineQuote({ combineId: this.row.combineId });
      // 刷列表 
      this.$table.search();
    },
    // 前往详情页
    goDetail (status, quotationId) {
      let query = {
        quotationId: quotationId || this.row.quotationId,
        combineId: this.row.combineId,
        subjectId: this.row.subjectId,
        surcharge: this.row?.surcharge,
        status: status
      };
      if (this.target === '_blank') {
        const { href } = this.$router.resolve({
          name: this.router || `oneBillQuote`,
          query
        });
        window.open(href, "_blank");
      } else {
        this.$router.push({
          name: "oneBillQuote",
          query
        });
      }
    },
    // 复制
    copy (val) {
      // 模拟 输入框
      var cInput = document.createElement("input");
      cInput.value = val;
      document.body.appendChild(cInput);
      cInput.select(); // 选取文本框内容 // 执行浏览器复制命令 // 复制命令会将当前选中的内容复制到剪切板中（这里就是创建的input标签） // Input要在正常的编辑状态下原生复制方法才会生效
      document.execCommand("copy");
      this.$message({ type: "success", message: "复制成功" });
      // 复制成功后再将构造的标签 移除
      document.body.removeChild(cInput);
    },
    // 分页数量改变
    handleSizeChange (value) {
      this.params.size = value;
    },
    // 当前页数改变
    handleCurrentChange (value) {
      this.params.page = value;
    }
  }
};
</script>
<style lang="scss" scoped>
.slot_sty {
  display: flex;
  align-items: center;
}
.linkClass {
  max-width: 160px !important;
  color: var(--prev-color-primary) !important;
  display: block;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  text-align: center;
}
.icon-sousuo {
  width: 12px !important;
  height: 12px !important;
  color: var(--prev-color-primary) !important;
}
.icon_sty {
  margin-left: 2px;
  margin-top: 3px;
  width: 18px;
  height: 18px;
  cursor: pointer;
  color: chocolate;
}
.icon_sty_1 {
  margin-left: 2px;
  margin-top: 3px;
  width: 16px;
  height: 16px;
  cursor: pointer;
  color: chocolate;
}
.titleSty {
  display: flex;
  justify-content: flex-start;
  font-size: 16px;
  height: 40px;
  line-height: 40px;
  color: var(--prev-color-primary);
}
.footerSty {
  display: flex;
  justify-content: space-between;
  font-size: 16px;
  height: 42px;
  line-height: 50px;
  color: var(--prev-color-text-darkgrey);
  .pagination {
    margin-top: 10px;
  }
}
.orange {
  color: var(--prev-color-primary);
}
.ml5 {
  margin-left: 5px;
}
.w10 {
  width: 10%;
}
.w88 {
  width: 88%;
}
</style>
